$(function () {
  //参数设置为全局对象，因为将来筛选和分页都要用
  let q = {
    pagenum: 1,
    pagesize: 10,
    cate_id: '',
    state: '',
  }

  //需求1   初始化文章列表
  initArticleList()
  function initArticleList() {
    axios({
      method: 'get',
      url: '/my/article/list',
      params: q,
    }).then(res => {
      if (res.data.status !== 0) return layer.msg(res.data.message)
      //渲染
      let arr = []
      res.data.data.forEach(ele => {
        arr.push(`
                <tr>
                <td> ${ele.title} </td>
                <td> ${ele.cate_name} </td>
                <td> ${formatDate(ele.pub_date)} </td>
                <td> ${ele.state} </td>
                <td>
                  <button class="layui-btn layui-btn-sm">编辑</button>
                  <button data-id=" ${
                    ele.Id
                  } " class=" del-btn layui-btn layui-btn-sm layui-btn-danger">删除</button>
                </td>
                </tr>
        `)
      })
      //赋值
      $('tbody').empty().html(arr.join(''))
      //分页
      renderPage(res.data.total)
    })
  }

  //需求2   渲染选中的文章
  initArtCateList()
  function initArtCateList() {
    axios({
      method: 'get',
      url: '/my/article/cates',
    }).then(res => {
      if (res.data.status !== 0) return layer.msg(res.data.message)
      //渲染
      let arr = ['<option value="">请选择文章所属分类</option>']
      res.data.data.forEach(ele => {
        arr.push(`<option value="${ele.Id}"> ${ele.name} </option>`)
      })
      //赋值
      let str = arr.join('')
      $('[name="cate_id"]').empty().html(str)
      //form.render()   可以渲染layui中的 select/checkbox/radio
      layui.form.render()
    })
  }

  //需求3   筛选
  $('#searchForm').on('submit', function (e) {
    e.preventDefault()
    q.cate_id = $('[name="cate_id"]').val()
    q.state = $('[name="state"]').val()
    //重新渲染
    initArticleList()
  })

  //需求4   分页
  function renderPage(total) {
    layui.laypage.render({
      elem: 'pageBox',
      count: total,
      limit: q.pagesize,
      curr: q.pagenum,
      layout: ['count', 'limit', 'prev', 'page', 'next', 'refresh', 'skip'],
      limit: [2, 3, 5, 10],
      jump: function (obj, first) {
        if (!first) {
          q.pagenum = obj.curr
          q.pagesize = obj.limit
          initArticleList()
        }
      },
    })
  }

  //需求5   删除
  $('tbody').on('click', '.del-btn', function () {
    let id = $(this).attr('data-id')
    layer.confirm('是否确认删除?', { icon: 3, title: '提示' }, function (index) {
      axios({
        url: '/my/article/delete/' + id,
        method: 'get',
      }).then(res => {
        //成功回调
        layer.msg('恭喜您!删除成功!')
        $('.del-btn').length == 1 && q.pagenum >= 2 && q.pagenum--
        initArticleList()
      })
      layer.close(index)
    })
  })
})
